package logic

import (
	"context"
	"fmt"
	"github.com/zeromicro/go-zero/core/logx"
	"origin/model/mysql"
	"origin/model/redisInit"
	"origin/originrpc/internal/svc"
	"origin/originrpc/originrpc"
	"origin/pkg"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

// 登录
func (l *LoginLogic) Login(in *originrpc.LoginRequest) (*originrpc.LoginResponse, error) {
	// todo: add your logic here and delete this line
	var phone mysql.Phone
	mysql.DB.Debug().Where("phone = ?").Find(&phone)
	if phone.ID == 0 {
		return nil, fmt.Errorf("手机号未注册,请重新输入")
	}
	m := mysql.Phone{
		Phone:    in.Phone,
		Password: in.Password,
	}
	err := mysql.DB.Debug().Create(&m).Error
	if err != nil {
		return nil, fmt.Errorf("注册失败")
	}
	get := redisInit.Client.Get("sendSms" + "login" + in.Phone)
	if get.Val() != in.SendSms {
		return nil, fmt.Errorf("短信验证码错误")
	}
	if phone.Password != pkg.MD5(in.Password) {
		return nil, fmt.Errorf("密码错误,请重新输入")
	}

	return &originrpc.LoginResponse{}, nil
}
